"""
Case Type   : 系统内部使用工具
Case Name   : 按流程执行：预安装-安装数据库-初始化数据库-卸载数据库-清理环境
Create At   : 2022/01/11
Owner       : @zou_jialiang0501129488
Description :
    1.下载解压数据库安装包
    2.配置xml文件,配置参数gaussdbLogPath
    3.修改新数据库文件属组为数据库初始用户
    4.gs_preinstall预安装：
    ./gs_preinstall -U [自定义初始用户] -G [自定义初始用户组] -X [xml配置文件路径]
    --sep-env-file=[env文件路径]
    5.gs_install安装1主1备：
    gs_install -X [xml配置文件路径]
    6.初始化数据库：gs_initdb -D [datadir] -w "passwd"
    7.gs_uninstall卸载数据库:gs_uninstall --delete-data
    8.postuninstall清理数据库环境：
    ./gs_postuninstall -U [自定义初始用户]  -X [xml配置文件路径]
    9.清理环境：
    rm -rf [数据库相关目录]
    userdel -rf 删除创建用户
Expect      :
    1.下载解压成功
    2.配置成功
    3.创建成功
    4.预安装成功
    5.安装成功
    6.初始化成功
    7.卸载成功
    8.清理成功
    9.清理成功
History     :
    modified by @daiguatutu at 2022-10-13:修改使用的macro中的密码参数，避免root密码和通用密码不一致执行失败
    modified by @daiguatutu at 2022-10-28:优化用例,增加预安装超时时间
    modified by @daiguatutu at 2022-11-4:添加hosts文件的备份和恢复，避免hosts文件被破坏
    modified by @daiguatutu at 2022-11-23:修改参数shared_buffers值,增加超时时间,避免性能问题安装失败
    modified by lonely-dance at 2025-3-25:优化安装包获取方式，增加恢复root互信操作，防止影响其他用例
"""
import os
import re
import unittest
from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
primary_sh = CommonSH('PrimaryDbUser')
Constant = Constant()


@unittest.skipIf(1 >= primary_sh.get_node_num(), '单机环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.standby1_root_node = Node('Standby1Root')
        self.standby1_node = Node('Standby1DbUser')
        self.u_name = 'postuninstall_case10'
        instance_path = macro.DB_INSTANCE_PATH
        for num in range(macro.DB_INSTANCE_PATH.count('/') - 1):
            instance_path = os.path.dirname(instance_path)
        self.dir_path = os.path.join(instance_path, self.u_name)
        self.package_path = os.path.join(self.dir_path, 'pkg')
        self.conf_path = os.path.join(self.dir_path, 'config')
        self.data_path = os.path.join(self.dir_path, 'cluster')
        self.xml_path = os.path.join(self.conf_path, 'primary_standby.xml')
        self.env_path = os.path.join(self.conf_path, 'env')
        self.script_path = os.path.join(self.package_path, 'script')
        self.instance_path = os.path.join(self.data_path, 'dn1')
        self.instance_path2 = os.path.join(self.data_path, 'dn2')

        text = '-----备份/etc/hosts文件-----'
        self.log.info(text)
        self.host_file = os.path.join('/', 'etc', 'hosts')
        self.host_bk = os.path.join(instance_path, 'hosts_bk')
        hosts_cmd = f"cp {self.host_file} {self.host_bk};"
        msg_pri = self.common.get_sh_result(self.primary_root_node, hosts_cmd)
        msg_sta = self.common.get_sh_result(self.standby1_root_node, hosts_cmd)
        self.assertEqual('', msg_pri and msg_sta, '执行失败:' + text)

    def test_gs_postuninstall(self):
        text = '-----step1:下载解压数据库安装包 expect:下载解压成功-----'
        self.log.info(text)
        self.common.get_package(self.primary_root_node, self.primary_root_node,
                                self.package_path, self.conf_path)

        text = '-----查看主机名-----'
        self.log.info(text)
        primary_node_name = self.common.get_sh_result(self.primary_root_node,
                                                      "uname -n")
        standby1_node_name = self.common.get_sh_result(self.standby1_root_node,
                                                       "uname -n")
        self.assertIsNotNone(primary_node_name, '执行失败:' + text)
        self.assertIsNotNone(standby1_node_name, '执行失败:' + text)
        text = '-----查询系统未使用端口-----'
        self.log.info(text)
        for count in range(10):
            port = self.common.get_not_used_port(self.primary_node)
            self.log.info(port)
            standby_port_check_cmd = f'netstat -tlnp | grep {port}'
            sta1_check_msg = self.common.get_sh_result(self.standby1_root_node,
                                                       standby_port_check_cmd)
            if not sta1_check_msg:
                self.assertNotEqual(0, port, '执行失败:' + text)
                break
            else:
                continue

        text = '-----step2:配置xml文件 expect:配置成功-----'
        self.log.info(text)
        gaussdb_app_path = os.path.join(self.data_path, 'app')
        gaussdb_log_path = os.path.join(self.data_path, 'gaussdb_log')
        tmpmppdb_path = os.path.join(self.data_path, 'tmp')
        gaussdb_tool_path = os.path.join(self.data_path, 'tool')
        self.common.scp_file(self.primary_root_node, 'primary_standby.xml',
                             self.conf_path)
        xml_cmd = \
            f"sed -i " \
            f"'s#v_nodeNames#{primary_node_name}, {standby1_node_name}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbAppPath#{gaussdb_app_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbLogPath#{gaussdb_log_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_tmpMppdbPath#{tmpmppdb_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_gaussdbToolPath#{gaussdb_tool_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_corePath#{macro.DB_CORE_PATH}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_db_host#{self.primary_node.db_host}, " \
            f"{self.standby1_node.db_host}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_pri_nodeNames#{primary_node_name}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_pri_db_host#{self.primary_node.db_host}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_dataPortBase#{port}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_dataNode1#" \
            f"{self.instance_path}, {standby1_node_name}, " \
            f"{self.instance_path}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_sta_nodeNames#{standby1_node_name}#g' " \
            f"{self.xml_path};" \
            f"sed -i 's#v_sta_db_host#{self.standby1_node.db_host}#g' " \
            f"{self.xml_path};" \
            f"cat {self.xml_path}"
        self.log.info(xml_cmd)
        result = self.common.get_sh_result(self.primary_root_node, xml_cmd)
        msg_list = [primary_node_name, standby1_node_name, self.data_path,
                    f"{port}", self.primary_node.db_host,
                    self.standby1_node.db_host]
        for content in msg_list:
            self.assertIn(content, result, 'xml构建失败')

        text = '-----step3:创建用户并修改文件属性 expect:成功-----'
        self.log.info(text)
        self.common.create_user(self.primary_root_node, self.u_name)
        self.common.create_user(self.standby1_root_node, self.u_name)
        file_own = f'chown -R {self.u_name}:{self.u_name} {self.dir_path}'
        self.log.info(file_own)
        file_msg = self.common.get_sh_result(self.primary_root_node, file_own)
        self.assertEqual('', file_msg, '执行失败:' + text)

        text = '-----step4:执行gs_preinstall命令 expect:预安装成功-----'
        self.log.info(text)
        preinstall_cmd = f'./gs_preinstall -U {self.u_name} ' \
                         f'-G {self.u_name} -X {self.xml_path}' \
                         f' --sep-env-file={self.env_path} --skip-hostname-set '
        execute_cmd = f'''cd {self.script_path}
                           expect <<EOF
                           set timeout 2000
                           spawn {preinstall_cmd}
                           expect "*(yes/no)?"
                           send "no\\n"
                           expect "*(yes/no)?"
                           send "yes\\n"
                           expect "Password:"
                           send "{macro.COMMON_PASSWD}\\n"
                           expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        msg = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.assertIn(Constant.preinstall_success_msg, msg,
                      '执行失败:' + text)

        text = '-----step5:执行gs_install安装数据库 expect:安装成功-----'
        self.log.info(text)
        su_cmd = f'su - {self.u_name}'
        install_cmd = f'gs_install -X {self.xml_path} ' \
            f'--dn-guc=shared_buffers=128MB'
        execute_cmd = f'''expect <<EOF
                   set timeout 600
                   spawn {su_cmd}
                   expect "$"
                   send "source {self.env_path}\\n"
                   expect "$"
                   send "{install_cmd}\\n"
                   expect "Please enter password for database:"
                   send "{macro.COMMON_PASSWD}\\n"
                   expect "Please repeat for database:"
                   send "{macro.COMMON_PASSWD}\\n"
                   expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        exec_msg = self.common.get_sh_result(self.primary_root_node,
                                             execute_cmd)
        self.assertIn(Constant.install_success_msg, exec_msg, text + '执行失败')

        text = '-----step6:执行gs_initdb初始化数据库 expect:成功-----'
        self.log.info(text)
        execute_cmd = f"su - {self.u_name} <<EOF\n" \
                      f"source {self.env_path};" \
                      f"gs_initdb -D {self.instance_path2} -w " \
                      f"'{macro.COMMON_PASSWD}' --nodename='sgnode';\n" \
                      f"EOF"
        self.log.info(execute_cmd)
        res = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        msg = 'Success. You can now start ' \
              'the database server of single node using:'
        self.assertIn(msg, res, 'init失败')

        text = '-----step7:执行gs_uninstall卸载数据库 expect:成功-----'
        self.log.info(text)
        execute_cmd = f'su - {self.u_name} <<EOF\n' \
                      f'source {self.env_path};' \
                      f'gs_uninstall --delete-data;\n' \
                      f'EOF'
        self.log.info(execute_cmd)
        res = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.assertIn(Constant.uninstall_success_msg, res, '数据库卸载失败')

        text = '-----step8:执行postuninstall命令 expect:成功-----'
        self.log.info(text)
        cmd = f"./gs_postuninstall -U {self.u_name} -X {self.xml_path}"
        execute_cmd = f'''source {self.env_path};
                       cd {self.script_path};
                       expect <<EOF
                       set timeout 600
                       spawn {cmd}
                       expect "*(yes/no)?"
                       send "no\\n"
                       expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        res = self.common.get_sh_result(self.primary_root_node, execute_cmd)
        self.assertIn('Successfully cleaned environment', res,
                      'postunisntall失败')

    def tearDown(self):
        text = "-----step9:清理用户及文件 expect:成功-----"
        self.log.info(text)
        text_1 = '-----恢复hosts文件 expect:成功-----'
        self.log.info(text_1)
        cmd = f'if [[ -e {self.host_file} && -e {self.host_bk} ]]; ' \
            f'then rm -rf {self.host_file}; ' \
            f'mv {self.host_bk} {self.host_file}; ' \
            f'else echo not exits; fi'
        hosts_msg_pri = self.common.get_sh_result(self.primary_root_node, cmd)
        hosts_msg_sta = self.common.get_sh_result(self.standby1_root_node, cmd)

        text_2 = '-----删除用户下进程 expect:成功-----'
        self.log.info(text_2)
        kill_flag = False
        dir_flag = False
        user_flag = False
        kill_cmd = f"ps -u {self.u_name} | grep -v PID | " \
                   f"awk \'{{{{print $1}}}}\' | xargs kill -9;" \
                   f"ipcs -m|awk '{{{{if($3~/^[0-9]+$/) {{{{print $2}}}}}}}}'" \
                   f" | xargs -I {{{{}}}} ipcrm -m {{{{}}}};" \
                   f"ipcs -s|awk '{{{{if($3~/^[0-9]+$/) {{{{print $2}}}}}}}}'" \
                   f" | xargs -I {{{{}}}} ipcrm -s {{{{}}}};sync;" \
                   f"echo 3 > /proc/sys/vm/drop_caches"
        self.log.info(kill_cmd)
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, kill_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, kill_cmd)
            if pri and sta1:
                self.log.info('process killed')
                kill_flag = True
                break
        text_3 = '----删除用户及数据准备目录 expect:成功----'
        self.log.info(text_3)
        check_cmd = f'rm -rf {self.dir_path};' \
                    f'if [ -d {self.dir_path} ]; ' \
                    f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(check_cmd)
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, check_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, check_cmd)
            if 'not exists' in pri and 'not exists' in sta1:
                self.log.info('file deleted')
                dir_flag = True
                break
        usr_cmd = f'userdel -rf {self.u_name};id {self.u_name}'
        for count in range(10):
            pri = self.common.get_sh_result(self.primary_root_node, usr_cmd)
            sta1 = self.common.get_sh_result(self.standby1_root_node, usr_cmd)
            if 'no such user' in pri and 'no such user' in sta1:
                self.log.info('user deleted')
                user_flag = True
                break

        text_4 = '----恢复root互信----'
        self.log.info(text_4)
        self.common.create_root_trust()

        self.assertEqual('', hosts_msg_pri and hosts_msg_sta, '执行失败:' + text_1)
        self.assertTrue(kill_flag, '清理环境失败')
        self.assertTrue(dir_flag, '清理环境失败')
        self.assertTrue(user_flag, '清理环境失败')
        self.log.info(f'-----{os.path.basename(__file__)} finish-----')
